import format from 'date-fns/format';

/**
 * 生成带前缀的一个唯一id
 *
 */
function genIDWithPrefix(prefix) {
    return ('' + prefix) + Number(Math.random().toString().substr(3,8) + Date.now()).toString(36);
}
/**
 * 生成数字的一个唯一id,使用36进制显示
 *
 */
function genNumberID() {
    return Number(Math.random().toString().substr(3,8) + Date.now()).toString(36);
}
/**
 * 将字符串转换成16进制的字符串,用于处理url传输问题(在微信中会进行转码,所以要处理)
 * @param {*} str 
 */
function stringToHexString(str) {
    //将字符串转换成Unit8Array
    const bytes = new TextEncoder().encode(str);
    let hexString = Array.from(new Uint8Array(bytes.buffer)).map(b=> b.toString(16).padStart(2, '0')).join('');
    console.log('stringToHexString==============2=', hexString);
    return hexString;
}
/**
 * 将16进制字符串转换成字符串
 * @param {*} hexString 
 * @returns 
 */
function hexStringToString(hexString) {
    console.log('hexStringToString==============1=', hexString);
    let str = String.fromCharCode(...hexString.match(/.{1,2}/g).map(byte=> parseInt(byte, 16)));
    console.log('hexStringToString==============2=', hexString);
    return str;
}
/**
 * 操作模式对话框显示的函数，目前用于VUE的Dialog，但是不依赖于VUE.
 * 此方法要删除,请使用showModalDialog
 * @param modalDialog
 * @param value
 */
function modalDialog(modalDialog, value) {
    if ( typeof value.visible !== undefined ) modalDialog.visible = value.visible;
    if ( typeof value.title !== undefined ) modalDialog.title = value.title;
    if ( typeof value.width !== undefined ) modalDialog.width = value.width;
    if ( typeof value.autoHeight !== undefined ) modalDialog.autoHeight = value.autoHeight;    
    if ( typeof value.contents !== undefined ) modalDialog.contents = value.contents;
    if ( typeof value.currentComponent !== undefined ) modalDialog.currentComponent = value.currentComponent;
}
/**
 * 操作模式对话框显示的函数，目前用于VUE的Dialog，但是不依赖于VUE.
 * @param {*} modalDialog 
 * @param {*} value 
 */
function showModalDialog(modalDialog, value) {
    if ( typeof value.visible !== 'undefined' ) modalDialog.visible = value.visible;
    if ( typeof value.helpDocCode !== 'undefined' ) modalDialog.helpDocCode = value.helpDocCode;
    if ( typeof value.title !== 'undefined' ) modalDialog.title = value.title;
    if ( typeof value.width !== 'undefined' ) modalDialog.width = value.width;
    if ( typeof value.autoHeight !== 'undefined' ) modalDialog.autoHeight = value.autoHeight;    
    if ( typeof value.contents !== 'undefined' ) modalDialog.contents = value.contents;
    if ( typeof value.currentComponent !== 'undefined' ) modalDialog.currentComponent = value.currentComponent;
}

/**
 * 关闭对话框,然后执行一个查询函数
 * @param {*} modalDialog 
 * @param {*} search 
 */
function closeDialog(modalDialog, search) {
    console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========1===');
    if ( modalDialog === undefined && search === undefined ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========2===');
    if ( modalDialog === null && search === null ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========3===');
    if ( typeof modalDialog !== 'object' ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========4===');
    if ( modalDialog !== null && typeof modalDialog.visible !== undefined ) {
        console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========当输出此消息，意为此对话框能正常关闭====4.1===');
        modalDialog.visible = false;
        console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========当输出此消息，意为此对话框能正常关闭====4.2===');
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeDialog=========5===');
    if ( typeof search === 'function' ) {
        search();
    }
}
function closeModalDialog(modalDialog, search, where) {
    console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========1===');
    if ( modalDialog === undefined && search === undefined && where === undefined ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========2===');
    if ( modalDialog === null && search === null && where === null ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========3===');
    if ( typeof modalDialog !== 'object' ) {
        return;
    }
    if ( typeof where !== 'object' ) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========4===');
    if ( modalDialog !== null && typeof modalDialog.visible !== undefined ) {
        console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========当输出此消息，意为此对话框能正常关闭====4.1===');
        modalDialog.visible = false;
        console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========当输出此消息，意为此对话框能正常关闭====4.2===');
    }
    console.log('zhdst-common-utils-js.CommonUtils.closeModalDialog=========5===');
    if ( typeof search === 'function' ) {
        search(where);
    }
}

/**
 * 
 * @param {*} where 查询条件
 * @param {*} data 事件传入的数据
 * @param {*} search 查询方法
 */
function tableSortChanged(where, data, search) {
    console.log('zhdst-common-utils-js.CommonUtils.tableSortChanged=========1==data=', data);
    if ( where === undefined || data === undefined || search === undefined) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.tableSortChanged=========2===');
    if ( where === null || data === null || search === null ) {
        return;
    }
    if ( typeof where === 'object' && typeof data === 'object' ) {
        if ( data.column.order ) {
            where.orderField = data.prop;
            where.orderType = data.order;
        }else {
            where.orderField = null;
            where.orderType = null;
        }
    }
    if ( typeof search === 'function' ) {
        search(where);
    }
}
/**
 * 当单元格 hover 进入时执行的方法
 * @param {*} row 
 * @param {*} column 
 * @param {*} cell 
 * @param {*} event 
 */
function cellMouseEnter(row, column, cell, event) {
    console.log('zhdst-common-utils-js.CommonUtils.cellMouseEnter=========1===', column, cell, event);
    row.displayIcon = true;
}
/**
 * 当单元格 hover 退出时执行的方法
 * @param {*} row 
 * @param {*} column 
 * @param {*} cell 
 * @param {*} event 
 */
function cellMouseLeave(row, column, cell, event) {
    console.log('zhdst-common-utils-js.CommonUtils.cellMouseLeave=========1===', column, cell, event);
    row.displayIcon = false;
}
function currentPageChanged(where, currentPage, search) {
    console.log('zhdst-common-utils-js.CommonUtils.currentPageChanged=========1==where, currentPage, search=', where, currentPage, search);
    if ( where === undefined || where.pageRange === undefined || currentPage === undefined || search === undefined) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.currentPageChanged=========2===');
    if ( where === null || where.pageRange === null || currentPage === null || search === null ) {
        return;
    }
    if ( where.pageRange ) {
        where.pageRange.currentPage = currentPage;
    }
    if ( typeof search === 'function' ) {
        search(where);
    }
}
function pageSizeChanged(where, pageSize, search) {
    console.log('zhdst-common-utils-js.CommonUtils.pageSizeChanged=========1==where, currentPage, search=', where, pageSize, search);
    if ( where === undefined || where.pageRange === undefined || pageSize === undefined || search === undefined) {
        return;
    }
    console.log('zhdst-common-utils-js.CommonUtils.pageSizeChanged=========2==');
    if ( where === null || where.pageRange === null || pageSize === null || search === null ) {
        return;
    }
    if ( where.pageRange ) {
        where.pageRange.pageSize = pageSize;
    }
    if ( typeof search === 'function' ) {
        search(where);
    }
}
/**
 * 删除数组中的元素，并减少数组的长度和索引。
 * @param elements
 * @param bpmnType
 */
function deleteElementsByType(elements, bpmnType) {
    //不能使用forEach,splice有坑. Shen Neo 2021-05-29
    for (let index = 0; index < elements.length; index++ ) {
        let element = elements[index];
        if ( element.$type === bpmnType ) {
            //删除旧的.
            elements.splice(index, 1);
            index = index - 1;
        }
    }
}

/**
 * 删除数组中的元素，并减少数组的长度和索引。
 * @param elements
 * @param bpmnType
 */
function deleteElementsById(elements, id) {
    //不能使用forEach,splice有坑. Shen Neo 2021-05-29
    for (let index = 0; index < elements.length; index++ ) {
        let element = elements[index];
        if ( element.id !== undefined && element.id === id ) {
            //删除旧的.
            elements.splice(index, 1);
            index = index - 1;
        }
    }
}

/*
* 参数说明：
* @param number：要格式化的数字
* @param decimals：保留几位小数
* @param dec_point：小数点符号
* @param thousands_sep：千分位符号
*
*/
function numberFormat(number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(n * k) / k;
        };

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
/**
 *
 * @param {Number} number
 * @param {String} dec_point
 * @param {String} thousands_sep
 * @returns
 */
function formatInteger(number, dec_point, thousands_sep) {
    return numberFormat(number, 0, dec_point, thousands_sep);
}
/**
 *
 * @param {Number} number
 * @param {String} dec_point
 * @param {String} thousands_sep
 * @returns
 */
function formatCurrency(number, dec_point, thousands_sep) {
    return numberFormat(number, 2, dec_point, thousands_sep);
}
/**
 * 
 * @param {*} date js支持的日期字符串或Date对象
 * @param {*} pattern js支持的日期格式字符串
 */
function formatDate(date, pattern) {
    if ( date === undefined || date === null || date === '') {
        return '';
    }
    if ( typeof date === 'string') {
        let dateObject = new Date(date);
        date = dateObject;
    }        
    return format(date, pattern);
}

/**
 * 
 * 校验菜单项与当前前端系统是否一致，一致则返回path.否则生成嵌入路径返回。
 * @param {*} menuItem 
 * 
 */
function getMenuPath(serviceWebCode, menuItem) {
    //如果是根菜单，则path=/
    if ( menuItem.path === undefined || menuItem.path === '' ) {
        return menuItem.path;
    }
    if ( menuItem.serviceWebCode === undefined || menuItem.serviceWebCode === '' ) {
        return menuItem.path;
    }
    if ( serviceWebCode === undefined || serviceWebCode === '' ) {
        return menuItem.path;
    }
    if ( serviceWebCode === menuItem.serviceWebCode ) {
        return menuItem.path;
    }
    if ( serviceWebCode !== menuItem.serviceWebCode ) {
        let embeddedPath = menuItem.path = '/embedded?url=' + menuItem.url;
        return embeddedPath;
    }
    return menuItem.path;

}

/**
 * 将租户ID和登录信息保存在key为zhdstLoginInfo中
 * @param {*} tenantId 
 * @param {String} jwt 
 */
function putToken(tenantId, jwt) {
    let zhdstLoginInfo = {tenantId: tenantId, jwt: jwt};
      //重要：这里一定要转换成字符串，否则sessionStorage保存时会转换成字符[object, object]
    sessionStorage.setItem('zhdstLoginInfo', JSON.stringify(zhdstLoginInfo));
}

/**
 * 从key为zhdstLoginInfo中取出登录信息。注意：不会取出租户ID
 * @returns 
 */
function getToken(){
    let info = JSON.parse(sessionStorage.getItem('zhdstLoginInfo'));
    if ( info ) {
        console.info('utils/index info.jwt ========' + info.jwt);
        return info.jwt;
    }
    return;
}
/**
 * 保存的Item='ZHDST_PAGE_' + CODE构成.目的是为了防止item重复而被覆盖
 * @param {*} code 
 */
/**
 * 
 * @param {*} code 
 * @param {*} value 
 */
function putPageProps(code, values) {
    if ( values === undefined || values === null ) {
        return;
    }
    let info = {code: code, values: values};
    //重要：这里一定要转换成字符串，否则localStorage保存时会转换成字符[object, object].使用sessionStorage,不使用localStorage，因为要考虑跨域问题
    sessionStorage.setItem('ZHDST_PAGE_' + code, JSON.stringify(info));
}
function getPageProps(code) {
    let info = JSON.parse(sessionStorage.getItem('ZHDST_PAGE_' + code));
    if ( info ) {
        console.info('utils/CommonUtils info.values ========' + info.values);
        return info.values;
    }
    return;
}

function putDatumBySnid(snid, datum) {
    if ( datum === undefined || datum === null ) {
        return;
    }
    let info = {snid: snid, datum: datum};
    //重要：这里一定要转换成字符串，否则localStorage保存时会转换成字符[object, object].使用sessionStorage,不使用localStorage，因为要考虑跨域问题
    sessionStorage.setItem('ZHDST_DATUM_' + snid, JSON.stringify(info));
}
function getDatumBySnid(snid) {
    let info = JSON.parse(sessionStorage.getItem('ZHDST_DATUM_' + snid));
    if ( info ) {
        console.info('utils/CommonUtils info.datum ========' + info.datum);
        return info.datum;
    }
    return;
}

/**
 * 
 * @param {*} index 
 * @param {Array} array 
 */
function arrayDown(index, array) {
    if ( (index < 0) || ((index + 1) >= array.length) ) {
        return array;
    }
    let current = array[index];
    array.splice(index, 1);
    array.splice(index + 1, 0, current);
    return array;
}
/**
 * 
 * @param {*} index 
 * @param {Array} array 
 */
function arrayUp(index, array) {
    if ( (index <= 0) || ((index + 1) > array.length) ) {
        return array;
    }
    let current = array[index];
    array.splice(index, 1);
    array.splice(index - 1, 0, current);
    return array
}
/**
 * 
 * @param {string} body 
 * @returns {textContent} textContent
 * @returns {Array} jsonContent
 */
function parseBody(body) {
    let result = {textContent: '', jsonContent: []};

    let parser = new DOMParser();
    let xmlDoc = parser.parseFromString('<expression>' + body + '</expression>', "text/xml");    
    let list = xmlDoc.getElementsByTagName('expression');
    console.log('xmlDoc==', xmlDoc);
    console.log('list==', list);
    for(let i = 0; i < list.length; i++){
        let row = list[i];
        let children = row.childNodes;
        console.log('row.textContent=====', row);
        console.log('row.textContent=====', row);
        console.log('row.children=====', children);
        if ( children.length > 0 ) {
            result.textContent = children[0].nodeValue;
        }
        if ( children.length > 1 ) {
            result.jsonContent = JSON.parse(children[1].nodeValue);
        }
        console.log('result=====', result);
        return result;
    }    
}
/**
 * 根据模式取出数据,然后按模式显示
 * @param {*} datum 
 * @param {*} pattern 
 */
function getByPatterns(datum, pattern) {
    let brackets = /\b(?=\w)\w+(?=}\$)/g;
    let vars = pattern.match(brackets);
    let result = pattern;
    vars.forEach(function (currentValue) {
        result = result.replace('${' + currentValue + '}$', (datum[currentValue] === undefined ? '' : datum[currentValue]));
    }, datum);
    return result;
}

let patterns = {
    'DATE_yyyy-MM-dd HH:mm': 'yyyy-MM-dd HH:mm',
    'DATE_yyyy-MM-dd': 'yyyy-MM-dd',
    'DATE_yy-MM-dd HH:mm': 'yy-MM-dd HH:mm',
    'DATE_yy-MM-dd': 'yy-MM-dd',
    'DATE_MM-dd HH:mm': 'MM-dd HH:mm',
    'name': '${name}$',
    'code': '${code}$',
    'name_code': '${name}$〖${code}$〗',
    'code_name': '〖${code}$〗${name}$',
};

export { patterns, genIDWithPrefix, genNumberID, stringToHexString, hexStringToString, showModalDialog, closeModalDialog, modalDialog, closeDialog, tableSortChanged, cellMouseEnter, cellMouseLeave, currentPageChanged, pageSizeChanged, 
    deleteElementsByType, deleteElementsById, numberFormat, formatInteger, formatCurrency, formatDate, getMenuPath, 
    putToken, getToken, putPageProps, getPageProps, putDatumBySnid, getDatumBySnid, arrayDown, arrayUp, parseBody, getByPatterns};
